package com.eduhzy.ttw.clazz.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.clazz.R;
import com.eduhzy.ttw.clazz.R2;
import com.eduhzy.ttw.clazz.di.component.DaggerClazzReportComponent;
import com.eduhzy.ttw.clazz.di.module.ClazzReportModule;
import com.eduhzy.ttw.clazz.mvp.contract.ClazzReportContract;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzReportHead;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzReportList;
import com.eduhzy.ttw.clazz.mvp.model.entity.HomeData;
import com.eduhzy.ttw.clazz.mvp.presenter.ClazzReportPresenter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-12-7 10:35:33
 */
@Route(path = RouterHub.CLAZZ_CLAZZREPORTFRAGMENT)
public class ClazzReportFragment extends BaseFragment<ClazzReportPresenter> implements ClazzReportContract.View {
    HomeData mBean;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @BindView(R2.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R2.id.tv_time)
    TextView mTvTime;
    private Calendar mCalendar;
    @Inject
    BaseQuickAdapter<ClazzReportList, AutoBaseViewHolder> mAdapter;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    private ViewHolder vh;
    private SimpleDateFormat mFormat;

    public static ClazzReportFragment newInstance(HomeData bean, int type) {
        ClazzReportFragment fragment = new ClazzReportFragment();
        try {
            HomeData newBean = (HomeData) bean.clone();
            newBean.setType(type);
            fragment.setData(newBean);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerClazzReportComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .clazzReportModule(new ClazzReportModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.clazz_fragment_clazz_report, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mFormat = new SimpleDateFormat("MM月dd日");
        mCalendar = Calendar.getInstance();
        getData(true);
        mRvList.setLayoutManager(mLayoutManager);
        mRvList.setAdapter(mAdapter);
        mSwipeLayout.setOnRefreshListener(() -> getData(true));
        mAdapter.setOnLoadMoreListener(() -> getData(false), mRvList);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
        });
    }


    private void getData(boolean pullToRefresh) {
        mPresenter.getClassData(pullToRefresh, mBean.getClassId(), mCalendar.getTimeInMillis(), mBean.getType());
    }


    @Override
    public void setData(@Nullable Object data) {
        if (ObjectUtils.isNotEmpty(data)) {
            mBean = (HomeData) data;
        }
    }

    @Override
    public void showLoading() {
        mSwipeLayout.setRefreshing(false);
        mEmptyView.show(true);
    }

    @Override
    public void hideLoading() {
        mSwipeLayout.setRefreshing(false);
        mEmptyView.hide();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @OnClick({R2.id.tv_pre, R2.id.tv_next})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_pre) {
            mCalendar.add(Calendar.WEEK_OF_YEAR, -1);
            getData(true);
        } else if (i == R.id.tv_next) {
            mCalendar.add(Calendar.WEEK_OF_YEAR, 1);
            getData(true);
        }
    }

    @Override
    public void updateHead(ClazzReportHead data) {
        Observable.just(1).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        updateListHead(data);
                    }
                });

    }

    private void updateListHead(ClazzReportHead data) {
        if (ObjectUtils.isNotEmpty(data)) {
            String start = TimeUtils.millis2String(data.getStartTime(), mFormat);
            String end = TimeUtils.millis2String(data.getEndTime(), mFormat);
            mTvTime.setText(start + "-" + end);

            if (mAdapter.getHeaderLayoutCount() <= 0) {
                View view = View.inflate(getActivity(), R.layout.clazz_rv_item_report_header, null);
                if (vh == null) {
                    vh = new ViewHolder(view);
                }
                mAdapter.addHeaderView(view);
            }
            vh.mBtnScore1.setText(data.getPraiseScore() > 0 ? "+" + data.getPraiseScore() : "0");
            vh.mBtnScore2.setText("" + data.getPraiseTimes());
            vh.mBtnScore3.setText(data.getImprovingScore() > 0 ? "-" + data.getImprovingScore() : "0");
            vh.mBtnScore4.setText("" + data.getImprovingTimes());
        } else {
            mAdapter.removeAllHeaderView();
            vh = null;
            mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
            mCalendar.set(Calendar.DAY_OF_WEEK, mCalendar.getFirstDayOfWeek());
            String start = TimeUtils.millis2String(mCalendar.getTimeInMillis(), mFormat);
            mCalendar.set(Calendar.DAY_OF_WEEK, mCalendar.getFirstDayOfWeek() + 6);
            String end = TimeUtils.millis2String(mCalendar.getTimeInMillis(), mFormat);
            mTvTime.setText(start + "-" + end);
            if (mAdapter.getHeaderLayoutCount() <= 0) {
                View view = View.inflate(getActivity(), R.layout.clazz_rv_item_report_header, null);
                if (vh == null) {
                    vh = new ViewHolder(view);
                }
                mAdapter.addHeaderView(view);
            }
            vh.mBtnScore1.setText("0");
            vh.mBtnScore2.setText("0");
            vh.mBtnScore3.setText("0");
            vh.mBtnScore4.setText("0");


        }
    }


    class ViewHolder {
        @BindView(R2.id.btn_score1)
        QMUIRoundButton mBtnScore1;
        @BindView(R2.id.btn_score2)
        QMUIRoundButton mBtnScore2;
        @BindView(R2.id.btn_score3)
        QMUIRoundButton mBtnScore3;
        @BindView(R2.id.btn_score4)
        QMUIRoundButton mBtnScore4;


        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
